angular.module('sqlite', [])
    .factory('sqlite', [
        '$cordovaSQLite', '$q', '$ionicLoading',
        function($cordovaSQLite, $q, $ionicLoading) {
            var prompt, sqlQuery;
            prompt = '未搜索到相关结果';
            sqlQuery = function(query) {
                var datas, deferred;
                deferred = $q.defer();
                datas = [];
                document.addEventListener('deviceready', function() {
                    $cordovaSQLite.execute(db, query, []).then(function(res) {
                        var i, length;
                        length = res.rows.length;
                        if (length > 0) {
                            i = 0;
                            while (i < length) {
                                datas.push(res.rows.item(i));
                                i++;
                            }
                            deferred.resolve(datas);
                        } else {
                            deferred.reject(prompt);
                        }
                        $ionicLoading.hide();
                    }, function(err) {
                        deferred.reject(prompt);
                        $ionicLoading.hide();
                    });
                }, false);
                return deferred.promise;
            };
            return {
                query: sqlQuery
            };
        }
    ]);
